class Room {
    constructor(pub) {
        this.mem = new Set()
        this.userList = []
        this.size = this.mem.size
        this.public = pub
    }
    fill(...members) {
        for (let i of members) {
            this.mem.add(i)
        }
        return this
    }
    join(item) {
        if (!this.public) {
            throw Error('无权进入房间')
            //TODO: 非公共房间检查权限
        }
        item && this.mem.add(item)
        return this
    }
    has(item) {
        return this.mem.has(item)
    }
    leave(item) {
        this.mem.delete(item)
        return this
    }
    async broadcast(fn) {
        for (let i of this.mem.values()) {
            await fn(i)
        }
    }
    members() {
        if (this.mem.size !== this.size) {
            let r = []
            for (let i of this.mem.values()){
                r.push(i.toSender())
            }
            this.userList = r
            this.size = this.mem.size
        }
        return this.userList
    }
    resetMemberCache() {
        this.size = null
    }
}

module.exports = Room